"""
提供解析Excel 数据 功能
"""

import os
from openpyxl import load_workbook
from openpyxl.workbook.workbook import Worksheet
import csv
from common.logger import logger

BaseDir = os.path.dirname(os.path.dirname(__file__))
dataDir = os.path.join(BaseDir,'data')


class FileHandler():

    def __init__(self):
        self.data_dir = dataDir

    def do_Excel(self,excelpath:str,sheetname:str):
        """
        读取Excel文件，文件内容默认按行读取，读取结果存放到 list中
        :param excelpath:
        :param sheetname:
        :return:
        """
        # testdata.xlsx 文件路径
        excel_file = os.path.join(self.data_dir,excelpath)
        # 加载Excel文件
        workbook = load_workbook(filename=excel_file)
        # 读取sheet
        worksheet: Worksheet = workbook[sheetname]
        logger.info(f"开始处理数据文件{excel_file},sheet工作表{sheetname}")
        lists = []
        for row in worksheet.iter_rows(min_col=1, min_row=2,
                                       max_row=worksheet.max_row,
                                       max_col=worksheet.max_column,
                                       values_only=True):
            print(row)
            lists.append(row)

        return lists


    def do_CSV(self,csvpath:str):
        """
        读取csv文件
        :param csvpath: csv文件路径
        :return: list数据格式
        """
        # csv 文件路径
        csv_file = os.path.join(self.data_dir,csvpath)
        testdata = []
        with open(csv_file,'r',encoding='utf8') as f:
            # 去掉表头
            f.readline()
            read = csv.reader(f)
            for line in read:
                testdata.append(line)
        return testdata

if __name__ == '__main__':
    fh = FileHandler()
    fh.do_Excel('testdata.xlsx','Sheet1')